<?php

class AdminController extends OController {

    public $homeUrl;
    public $addNewUrl;
    public $cancelUrl;
    public $sendActivationMailUrl;
    public $resetPasswordUrl;
    public $sendWelcomeMailUrl;
    
    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    public function init(){
        parent::init();
        $this->homeUrl=$this->createUrl($this->id.'/'.$this->defaultAction);
        $this->addNewUrl=$this->createUrl($this->id.'/create');
        $this->breadcrumbs=array(
            Lang::t('admin.list.page.title')=>$this->homeUrl,
        );
    }
    
    public function actionAdmin() {
        $model = new User('adminSearch');
        $model->unsetAttributes();  // clear any default values
        
        $address=new Address;
        
        $params = Yii::app()->request->getParam(get_class($model));
        if ($params)
            $model->attributes=$params;

        $this->render('admin', array(
            'model' => $model,
            'address'=>$address,
            'dataProvider'=>$model->search('admin'),
        ));
    }

    public function actionView($id) {
        $this->render('view', array(
            'data' => $this->loadModel($id),
        ));
    }

    public function actionCreate() {
        $model = new User('adminRegister');
        $model->autoFill();
        $address=new Address;
        $address->autoFill($model);
        //$address->validatorList->add(CValidator::createValidator('required', $address, 'address_'));
        $this->performAjaxValidation($model,$address);

        $params = Yii::app()->request->getParam(get_class($model));
        $addressParams = Yii::app()->request->getParam(get_class($address));
        if ($params && $addressParams) {
            $model->attributes=$params;
            $model->image_ = CUploadedFile::getInstances($model, 'image_');
            $model->validate();
            $address->attributes=$addressParams;
            $address->validate();
            
            if(!$model->hasErrors() && !$address->hasErrors() && $model->addRecord($address)){
                if (Yii::app()->params['userOptInMode']) {
                    $email = new Email;
                    $email->to = array($model->email => $model->name);
                    $email->params = array('data' => $model);
                    $email->subject = Lang::t('register.mail.notify.user.subject', array('{domainname}' => Yii::app()->request->hostInfo));
                    $email->view = 'user.registerWelcomeNote';
                    $email->send();
                }//end if
                $this->setFlash('success', Lang::t('user.register.flash.success'));
                $this->redirect(array('update', 'id' => $model->id));
            }          
        }

        $this->render('createForm', array(
            'user' => $model,
            'address'=>$address,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'htmlOptions' => array(
                    'enctype' => 'multipart/form-data',
                ),
                'focus' => array($model, 'firstName_'),
            ),
        ));
    }
    
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        $model->scenario = 'adminUpdate';
        $model->autoFill();

        $address=empty($model->address)?new Address:$model->address;
        $address->autoFill($model);
        //$address->validatorList->add(CValidator::createValidator('required', $address, 'address_'));
        
        $this->performAjaxValidation($model,$address);

        $params = Yii::app()->request->getParam(get_class($model));
        $addressParams=Yii::app()->request->getParam(get_class($address));
        if ($params && $addressParams) {
            $model->attributes=$params;
            $model->image_ = CUploadedFile::getInstances($model, 'image_');
            $model->validate();
            $address->attributes=$addressParams;
            $address->validate();
            
            if (!$model->hasErrors() && !$address->hasErrors() && $model->updateRecord($address)) {
                $this->setFlash('success', Lang::t('user.profile.flash.success'));
                $this->refresh();
            }else{
                $this->setFlash('error', Lang::t('user.profile.flash.fail'));
            }
        }

        $this->sendWelcomeMailUrl = $this->createUrl('sendwelcomemail', array('id'=>$model->id));
        $this->sendActivationMailUrl = $this->createUrl('sendactivationmail', array('id'=>$model->id));
        $this->resetPasswordUrl = $this->createUrl('resetPassword', array('id'=>$model->id));
        $this->render('updateForm', array(
            'user' => $model,
            'address'=>$address,
            'formConfig' => array(
                'id' => $this->formId,
                'enableAjaxValidation' => true,
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                ),
                'htmlOptions' => array(
                    'enctype' => 'multipart/form-data',
                ),
                'focus' => array($model, 'firstName_'),
            ),
        ));
    }

    public function actionResetpassword($id){
        $model = $this->loadModel($id); $success=false;
        if($model->resetPassword() && $model->refresh()){
            $email = new Email;
            $email->to = array($model->email => $model->name);
            $email->params = array('data' => $model);
            $email->subject = Lang::t('user.profile.mail.notify.reset.password.subject');
            $email->view = 'user.passwordRecovery';
            $email->send();
            $success=true;
        }
        if($success){
            $this->setFlash('success', Lang::t('user.profile.flash.reset.password.success'));
        }else{
            $this->setFlash('error', Lang::t('user.profile.flash.reset.password.fail'));
        }
        $this->redirect(Yii::app()->request->urlReferrer);
    }

    public function actionSendwelcomemail($id){
        $model = $this->loadModel($id); $success=false;
        if($model->resetPassword() && $model->refresh()){
            $email = new Email;
            $email->to = array($model->email => $model->name);
            $email->params = array('data' => $model);
            $email->subject = Lang::t('user.profile.mail.notify.owd.welcome.subject');
            $email->view = 'user.owdWelcomeNote';
            $email->send();
            $success=true;
        }
        if($success){
            $this->setFlash('success', Lang::t('user.profile.flash.reset.password.success'));
        }else{
            $this->setFlash('error', Lang::t('user.profile.flash.reset.password.fail'));
        }
        $this->redirect(Yii::app()->request->urlReferrer);
    }
    
    public function actionSendactivationmail($id){
        $model = $this->loadModel($id); $success=false;
        if($model->resetActivationCode()){
            $email = new Email;
            $email->to = array($model->email => $model->name);
            $email->params = array('data' => $model);
            $email->subject = Lang::t('user.register.mail.notify.user.subject', array('{domainname}' => Yii::app()->request->hostInfo));
            $email->view = 'user.registerWelcomeNote';
            $email->send();
            $success=true;
        }
        if($success){
            $this->setFlash('success', Lang::t('user.profile.flash.send.activation.mail.success'));
        }else{
            $this->setFlash('error', Lang::t('user.profile.flash.send.activation.mail.fail'));
        }
        $this->redirect(Yii::app()->request->urlReferrer);
    }    
    
    public function actionDelete($id) {
        $model = $this->loadModel($id);
        $model->scenario='adminDelete';
        if ($model->deleteRecord()) {
            $this->setFlash('success', Lang::t('user.delete.success'));
        } else {
            $this->setFlash('fail', Lang::t('user.delete.fail'));
        }
        
        //$this->redirect(array('admin'));
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel($id = null) {
        if ($this->_model === null) {
            if (!empty($id))
                $this->_model = User::model()->accessible()->findByPk((int) $id);

            if ($this->_model === null)
                HttpStatus::code(404);
        }
        return $this->_model;
    }

}//end class